<?php


namespace App\Web\Controller;

use App\Facades\Captcha;
use App\Service\ImgCaptcha;
use App\Web\Model\Attach;
use App\Web\Model\Operator as OprModel;
use App\Web\Model\Resume as ResumeModel;
use EchoPHP\Http\Request;
use App\Web\Model\Login as LoginModel;
use EchoPHP\Http\Response\JsonResponse;
use EchoPHP\Http\Response\StreamedResponse;

class Login extends BaseController {

    /**
     * 用户登录
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function login(Request $request) {
        $userName = $request->getPost('username');
        $password = $request->getPost('password');

        $loginModel = new LoginModel();
        $loginResult = $loginModel->login($userName, $password);

        return $this->json($loginResult);
    }

    /**
     *手机号登录
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function phoneLogin(Request $request) {
        $telPhone = $request->getParam('telphone');
        $verifyCode = $request->getParam('verifycode');

        $loginModel = new LoginModel();
        $loginResult = $loginModel->loginByPhone($telPhone, $verifyCode);
        return $this->json($loginResult);
    }

    /**
     * 顶替其他终端的登录状态
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function replace(Request $request) {
        $refreshToken = $request->getPost('refreshToken');
        $loginModel = new LoginModel();
        $loginResult = $loginModel->replaceLogin($refreshToken);
        return $this->json($loginResult);
    }

    /**
     * 用户注销登录
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function logout() {
        $loginId = $this->getLoginId();
        if ($loginId == 0) {
            return $this->json(['status' => true, 'message' => '操作成功']);
        }
        $loginModel = new LoginModel();
        $loginModel->logout($loginId);
        return $this->json(['status' => true, 'message' => '操作成功']);
    }

    /**
     * 获取非对称加密公钥
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function publickey() {
        $publicKey = file_get_contents(config('app.jwt.public_key'));
        return $this->json(['status' => true, 'message' => '操作成功', 'publicKey' => $publicKey]);
    }

    /**
     * 获取并输出图形验证码
     * @param Request $request
     * @return StreamedResponse
     * @throws \Exception
     */
    public function verifyimg(Request $request) {
        $uuid = $request->getParam('uuid');
        $action = $request->getParam('act', 'login');
        $uuid .= '_' . $action;
        $result = Captcha::generate('image', $uuid);

        $imgCaptcha = new ImgCaptcha();
        //输出普通复杂度的图片
        $options = [
            'level' => 2,
            'type' => 'img'
        ];
        return $imgCaptcha->response($result['code'], $options);
    }

    /**
     * 图形验证码预校验
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function preChkImgVerify(Request $request) {
        $verifyCode = $request->getParam('verifycode');
        $uuid = $request->getParam('uuid');
        $action = $request->getParam('act', 'login');
        $uuid .= '_' . $action;
        $result = Captcha::check('image', $uuid, $verifyCode, true);
        return $this->json(['status' => $result ? true : false, 'message' => '']);
    }

    /**
     * 发送短信验证码
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function verifySms(Request $request) {
        $uuid = $request->getParam('uuid');
        $telPhone = $request->getParam('telphone');
        $verifyCode = $request->getParam('verifycode');

        $loginModel = new LoginModel();
        $result = $loginModel->sendMpLoginCode($uuid, $verifyCode, $telPhone);
        return $this->json($result);
    }

    /**
     * 找回密码 向用户的注册邮箱发送修改密码的链接，链接带用户工号和唯一编码
     * @param \EchoPHP\Http\Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function sendPasswdEmail(Request $request) {
        $userName = $request->getParam('username');
        $oprModel = new OprModel();
        $result = $oprModel->sendPasswdEmail($userName);
        return $this->json($result);
    }

    /**找回密码 用户通过邮箱验证后修改密码
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function resetPwd(Request $request) {
        $verify = $request->getParam('verify');
        $username = $request->getParam('username');
        $newPasswd = $request->getPost('newpasswd');
        $confirmPasswd = $request->getPost('confirmpasswd');
        $oprModel = new OprModel();
        $result = $oprModel->chkVerify($verify, $username);
        if ($result['status'] == false) {
            return $this->json([
                'status' => false,
                'message' => $result['message'],
            ]);
        }
        $result = $oprModel->forgetPasswd($username, $newPasswd, $confirmPasswd);
        return $this->json($result);
    }

    // 下载简历附件(测试工具，取消登录验证，供机器学习调用)
    public function downloadResumeAttach(Request $request) {
        $resumeAttachId = $request->getParam('resumeattachid');
        $file = (new ResumeModel())->getAttachPath($resumeAttachId);
        if (empty($file)) {
            return $this->json(
                ['status' => false,
                    'message' => '附件不存在'
                ]
            );
        }

        $filePath = FILESERVER . '/' . $file['filepath'];
        if (!$file || !file_exists($filePath)) {
            return $this->json(
                [
                    'status' => false,
                    'message' => '下载错误'
                ]
            );
        }
        return response()->download($filePath, '简历附件-' . $file['attachname']);
    }
}